import { CanvasSource } from "pixi.js";
import { Sprite } from "@/sprites/Sprite.js";

export class Sprite_Destination extends Sprite {
    constructor(width,height) {
        let canvasSource=new CanvasSource({width,height});
        super(canvasSource);
        this.canvasSource=canvasSource;
        this.context=canvasSource.context2D;
        this.anchor.set(0.5,0.5);
        this.blendMode='add';

        this.frameCount=0;

        this.active=false;

        this.dx=null;
        this.dy=null;

        this.fillSelf();
        this.attachHandler();
    }

    destroy(opts){
        this.deattachHandler();
        super.destroy(opts);
    }

    attachHandler(){
        $gameTemp.on('temp:destionation',this.onDestionation);        
    }
    deattachHandler(){
        $gameTemp.off('temp:destionation',this.onDestionation);
    }

    onDestionation=(type)=>{
        if(type=='active'){
            this.activate();
            this.setDestination(
                $gameMap.adjustX($gameTemp.destinationX()),
                $gameMap.adjustY($gameTemp.destinationY())
            );
        }else if(type=='deactive'){
            this.deactivate();
        }
        
    }

    fillSelf(color){
        this.context.fillStyle=color??'#fff';
        this.context.fillRect(0,0,this.width,this.height);
        this.canvasSource.update();
    }

    setDestination(x,y){
        if(this.dx!=x||this.dy!=y){
            this.dx=x;
            this.dy=y;
            this.x=(x+0.5)*this.canvasSource.width;
            this.y=(y+0.5)*this.canvasSource.height;
        }
    }
    activate(){
        if(!this.active){
            this.active=true;
            this.visible=true;
            this.frameCount=0;
        }
    }

    deactivate(){
        this.active=false;
        this.visible=false;
        this.dx=null;
        this.dy=null;
    }

    update() {
        super.update();
        if(this.active){
            this.updateAnimation();
        }
    }

    updateAnimation() {
        ++this.frameCount;
        this.frameCount %= 20;
        this.alpha = (120 - 6*this.frameCount)/255;
        this.scale.set(1 + this.frameCount / 20);
    }
}